package com.xq.handler;

import com.xq.config.SessionContants;
import com.xq.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 登录拦截
public class AdminLoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("x-frame-options", "SAMEORIGIN");
        // 获取 loginUser 信息进行判断
        User user = (User) request.getSession().getAttribute(SessionContants.LOGIN_USER);
        if (user == null) { // 未登录，返回登录页面
            request.setAttribute("msg", "没有权限，请先登录");
            response.sendRedirect("/admin/login");
            return false;
        } else {
            // 只有管理员才有资格进入
            if (user.getRole() != null && user.getRole().equals("admin")) {
                UserThreadLocal.put(user);
                return true;
            } else {
                request.setAttribute("msg", "没有权限，请先登录");
                response.sendRedirect("/admin/nopermission");
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    // 此处两个方法，一定都是要preHandle方法返回为true的时候执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserThreadLocal.remove();
    }
}